package com.example.demosbtmongodb.test;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author wangbin
 */
@RestController
public class CustomController {
    @Resource
    CustomerRepository customerRepository;

    @GetMapping("/")
    public ModelAndView index(Map<String, Object> model) {
        List<Customer> list = customerRepository.findAll();
        model.put("list", list);
        return new ModelAndView("index", model);
    }

    @GetMapping("/create")
    public ModelAndView create(Map<String, Object> model) {
        return new ModelAndView("update", model);
    }

    @GetMapping("/update/{id}")
    public ModelAndView update(Map<String, Object> model, @PathVariable String id) {
        Customer customer = customerRepository.findById(id).orElseThrow(RuntimeException::new);
        model.put("data", customer);
        return new ModelAndView("update", model);
    }

    @PostMapping("/save")
    public ModelAndView save(Customer customer) {
        customerRepository.save(customer);
        return new ModelAndView("redirect:/");
    }

    @GetMapping("/deleteById/{id}")
    public ModelAndView deleteById(@PathVariable String id) {
        customerRepository.deleteById(id);
        return new ModelAndView("redirect:/");
    }

    @GetMapping("/findByFirstName")
    public Customer findByFirstName(String firstName) {
        return customerRepository.findByFirstName(firstName);
    }

    @GetMapping("/findByLastName")
    public List<Customer> findByLastName(String lastName) {
        return customerRepository.findByLastName(lastName);
    }


}
